﻿using AchieveBLL;
using AchieveCommon;
using AchieveEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

namespace AchieveManageWeb.Controllers
{
    [AchieveManageWeb.App_Start.JudgmentLogin]
    public class PMCostController : Controller
    {
        //
        // GET: /PMCost/

        public ActionResult Index()
        {
            return View();
        }

        //public ActionResult getworktypelist()
        //{
        //    string sql = "select distinct worktype from tbPartEstP";
        //    DataTable dt = SqlHelper.GetDataTable(SqlHelper.connStr, sql);
        //    string strJson = JsonHelper.ToJson(dt);
        //    return Content(strJson);
        //}
        public ActionResult getparttypelist()
        {
            ///PMCost/getparttypelist?worktype=' + codename;
            string worktype = Request["worktype"] == null ? "0" : Request["worktype"];
            string sql = string.Format("select distinct parttype as codename from tbPartEstP where workType='{0}'", worktype);
            DataTable dt = SqlHelper.GetDataTable(SqlHelper.connStr, sql);
            string strJson = JsonHelper.ToJson(dt);
            return Content(strJson);
        }
        public ActionResult getclasstypelist()
        {
            //  var url = '/PMCost/getclasstypelist?parttype=' + value;
            string parttype = Request["parttype"] == null ? "0" : Request["parttype"];
            string sql = string.Format("select classtype as codename,price from tbPartEstP where parttype='{0}'", parttype);
            DataTable dt = SqlHelper.GetDataTable(SqlHelper.connStr, sql);
            string strJson = JsonHelper.ToJson(dt);
            return Content(strJson);
        }

        /// <summary>
        /// 根据传入的projectid获取估算成本清单；
        /// </summary>
        /// <returns></returns>   
        public ActionResult getEstCostRows()
        {
            string ProjectID = string.IsNullOrWhiteSpace(Request["ProjectID"]) ? "201904090001" : Request["ProjectID"];
            string sql = string.Format("select * from tbProjectCostEntry where projectid='{0}'", ProjectID);
            DataTable dt = SqlHelper.GetDataTable(SqlHelper.connStr, sql);
            int totalCount = dt.Rows.Count;
            string strJson = JsonHelper.ToJson(dt);
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }
        /// <summary>
        /// 保存估算成本的记录行
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveEstCostEntry()
        {
            //ProjectID: ProjectID,
            //           entryid:row.entryid,
            //           worktype:row.worktype,
            //           parttype:row.parttype,
            //           classtype:row.classtype,
            //           price:row.price,
            //           weight:row.weight,
            //           cost:row.cost,
            //           totalcost:row.totalcost
            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            Int32 entryid = string.IsNullOrWhiteSpace(Request["entryid"]) ? 0 : Convert.ToInt32(Request["entryid"]);
            string worktype = Request["worktype"] == null ? "" : Request["worktype"];
            string parttype = Request["parttype"] == null ? "" : Request["parttype"];
            string classtype = Request["classtype"] == null ? "" : Request["classtype"];
            string price = Request["price"] == null ? "" : Request["price"];
            decimal weight = string.IsNullOrWhiteSpace(Request["weight"]) ? 0 : Convert.ToDecimal(Request["weight"]);
            decimal cost = Request["cost"] == null ? 0 : Convert.ToDecimal(Request["cost"]);
            decimal totalcost = Request["totalcost"] == null ? 0 : Convert.ToDecimal(Request["totalcost"]);
            string method = Request["method"] == null ? "" : Request["method"];
            UserEntity uInfo = ViewData["Account"] as UserEntity;
          
            if (ProjectID != "")
            {
                string sql;
                if (entryid > 0)//更新
                { 
                    sql = @"update tbProjectCostEntry set worktype=@worktype,parttype=@parttype,classtype=@classtype,price=@price,weight=@weight,cost=@cost, 
                               UpdateBy=@UpdateBy,UpdateTime=@UpdateTime 
                                where entryid=@entryid; ";
                    if (method == "delete")//删除分录
                    {
                        sql = @"delete tbProjectCostEntry  where entryid=@entryid; ";
                    }

                }
                else//新增
                {
                    sql = @"insert into tbProjectCostEntry(ProjectID,worktype,parttype,classtype,price,weight,cost,UpdateBy,UpdateTime)
                                values(@ProjectID, @worktype, @parttype, @classtype, @price, @weight, @cost,@UpdateBy,@UpdateTime)";
                }

                SqlParameter[] paras = { 
                                   new SqlParameter("@entryid",SqlDbType.Int),
                                   new SqlParameter("@worktype",SqlDbType.VarChar,50),
                                   new SqlParameter("@parttype",SqlDbType.VarChar,50),
                                   new SqlParameter("@classtype",SqlDbType.VarChar,50),
                                   new SqlParameter("@price",SqlDbType.Decimal),
                                   new SqlParameter("@weight",SqlDbType.Decimal),
                                    new SqlParameter("@cost",SqlDbType.Decimal),
                                   new SqlParameter("@UpdateTime",SqlDbType.DateTime),
                                   new SqlParameter("@UpdateBy",SqlDbType.NVarChar,100),
                                    new SqlParameter("@totalcost",SqlDbType.Decimal),
                                     new SqlParameter("@ProjectID",SqlDbType.VarChar,50),
                                   };
                paras[0].Value = entryid;
                paras[1].Value = worktype;
                paras[2].Value = parttype;
                paras[3].Value = classtype;
                paras[4].Value = price;
                paras[5].Value = weight;
                paras[6].Value = cost;
                paras[7].Value = DateTime.Now;
                paras[8].Value = uInfo.AccountName;
                paras[9].Value = totalcost;
                paras[10].Value = ProjectID;
                 
                
                object obj = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, sql, paras);
                if (Convert.ToInt32(obj) == 0)
                { return Content("{\"msg\":\"服务器更新分录失败！\",\"success\":false}"); }
                else
                {
                    //保存汇总估算成本
                    sql = @"   if not exists (select ProjectID from tbProjectCost where ProjectID = @ProjectID )
                                                      insert into tbProjectCost(ProjectID, estCost,UpdateBy,UpdateTime) values(@ProjectID, @totalcost,@UpdateBy,@UpdateTime)
                                                   else
                                                      update tbProjectCost set estCost=@totalcost,UpdateBy=@UpdateBy,UpdateTime=@UpdateTime  where ProjectID =@ProjectID
                                                ";
                    obj = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, sql, paras);
                    if (Convert.ToInt32(obj) == 0)
                    { return Content("{\"msg\":\"服务器更新估算成本记录失败！\",\"success\":false}"); }
                    else
                    {
                        return Content("{\"msg\":\"服务器更新数据成功！\",\"success\":true}");
                    }
                }


            }
            else
            {
                return Content("{\"msg\":\"服务器保存数据失败，未能获取项目id！\",\"success\":false}");
            }


        }

        
             /// <summary>
        /// 保存标准成本的记录行
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveStdCostEntry()
        { 
            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            string FitemNo = Request["FitemNo"] == null ? "" : Request["FitemNo"];
             string FName = Request["FName"] == null ? "" : Request["FName"];
             string FModel = Request["FModel"] == null ? "" : Request["FModel"];

             if (SqlInjection.GetString(ProjectID) && SqlInjection.GetString(FitemNo) && SqlInjection.GetString(FName) && SqlInjection.GetString(FModel))
             {
                 return Content("{\"msg\":\"参数中存在非法字符，有sql注入风险！\",\"success\":false}");
            } 
     
           

            decimal stdCost = Request["stdCost"] == null ? 0 : Convert.ToDecimal(Request["stdCost"]);
            string method = Request["method"] == null ? "" : Request["method"];
            UserEntity uInfo = ViewData["Account"] as UserEntity;
          
            if (ProjectID != "")
            {
                string sql;
                    //保存标准成本
                    SqlParameter[] paras = {                                  
                                   new SqlParameter("@UpdateTime",SqlDbType.DateTime),
                                   new SqlParameter("@UpdateBy",SqlDbType.NVarChar,100),
                                    new SqlParameter("@stdCost",SqlDbType.Decimal),
                                     new SqlParameter("@ProjectID",SqlDbType.VarChar,50),
                                      new SqlParameter("@FitemNo",SqlDbType.VarChar,50),
                                      new SqlParameter("@FName",SqlDbType.VarChar,50),
                                      new SqlParameter("@FModel",SqlDbType.VarChar,50),
                                   };
  
                paras[0].Value = DateTime.Now;
                paras[1].Value = uInfo.AccountName;
                paras[2].Value = stdCost;
                paras[3].Value = ProjectID;
                paras[4].Value = FitemNo;
                paras[5].Value = FName;
                paras[6].Value = FModel;
                //更新项目主表和成本表
                sql = @"  update tbProject set FitemNo=@FitemNo,FModel=@FModel,FName=@FName where ProjectID = @ProjectID ;
                                if not exists (select ProjectID from tbProjectCost where ProjectID = @ProjectID )
                                                      insert into tbProjectCost(ProjectID, stdCost,UpdateBy,UpdateTime) values(@ProjectID, @stdCost,@UpdateBy,@UpdateTime)
                                                   else
                                                      update tbProjectCost set stdCost=@stdCost,UpdateBy=@UpdateBy,UpdateTime=@UpdateTime  where ProjectID =@ProjectID
                                                "; 

                    if (SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, sql, paras) == 0)
                    { return Content("{\"msg\":\"服务器更新估算成本记录失败！\",\"success\":false}"); }
                    else
                    {
                        return Content("{\"msg\":\"服务器更新数据成功！\",\"success\":true}");
                    }
    

            }
            else
            {
                return Content("{\"msg\":\"服务器保存数据失败，未能获取项目id！\",\"success\":false}");
            }


        }


        /// <summary>
        /// 计算和保存实际成本
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveReaCostEntry()
        { 
            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ficmono = Request["ficmono"] == null ? "" : Request["ficmono"];
           
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            try
            {
                if (ProjectID != "")
                {
                    //计算实际成本
                    decimal ReaCost = AchieveBLL.CostBLL.realCostCal(ficmono);
                    //更新项目主表 及 保存标准成本
                    if(AchieveBLL.CostBLL.updateProjectRealCost(uInfo.AccountName,ReaCost,ProjectID,ficmono)==0)
                    { return Content("{\"msg\":\"服务器更新估算成本记录失败！\",\"success\":false}"); }
                    else
                    {
                        return Content("{\"msg\":" + ReaCost + ",\"success\":true}");
                    }

                }
                else
                {
                    return Content("{\"msg\":\"服务器保存数据失败，未能获取项目id！\",\"success\":false}");
                }
            }
            catch (Exception e)
            {

                return Content("{\"msg\":\"出现异常！"+e.Message+"\",\"success\":false}");
            } 

        }
        /// <summary>
        /// 角色权限--成本字段查看
        /// </summary>
        /// <returns></returns>
        public ActionResult SetRoleField()
        {
            try
            {
                // string UserIDs = Request["UserIDs"] ?? "";  //用户id，可能是多个 
                string field = Request["fieldName"] ?? "";  //用户id，可能是多个
                string roleIds = Request["RoleIDs"] ?? "";  //角色id，可能是多个
                if (field != "")
                {
                    List<string> role_addList = new List<string>(); //需要插入角色的sql语句集合 
                    string[] str_role = roleIds.Trim(',').Split(',');    //传过来用户勾选的角色（有去勾的也有新勾选的）
                    role_addList.Add(string.Format("delete tbRoleField where fieldName='{0}' and pageName='PMIndex';", field));
                    for (int i = 0; i < str_role.Length; i++)
                    {
                        role_addList.Add(string.Format("insert into [tbRoleField](roleId,fieldName,pageName) values('{0}','{1}','PMIndex');", str_role[i], field));
                    }
                    if (SqlHelper.ExecuteNonQuery(SqlHelper.connStr, role_addList) > 0)
                    {
                        return Content("{\"msg\":\"设置成功！\",\"success\":true}");
                    }
                    else
                    {
                        return Content("{\"msg\":\"设置失败！\",\"success\":true}");
                    }

                }
                else
                {
                    return Content("{\"msg\":\"设置失败！\",\"success\":true}");
                }

            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"设置失败," + ex.Message + "\",\"success\":false}");
            }
        }
        /// <summary>
        /// 根据字段获取授权的角色
        /// </summary>
        /// <returns></returns>
        public ActionResult getFieldRoles() {

            try
            { 
                string field = Request["fieldName"] ?? "";  //用户id，可能是多个 
                if (field != "")
                {
                    string sql=string.Format("select roleid from tbRoleField where  fieldName='{0}' and pageName='PMIndex';", field);
                    DataTable dtrole = SqlHelper.GetDataTable(SqlHelper.connStr, sql);
                   string roles= AchieveCommon.JsonHelper.ColumnToJson(dtrole, 0);
                   
                        return Content("{\"msg\":\""+roles+"\",\"success\":true}");
                    

                }
                else
                {
                    return Content("{\"msg\":\"获取数据失败！\",\"success\":true}");
                }

            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"获取数据失败," + ex.Message + "\",\"success\":false}");
            }
        
        }

    }
}
